using Lzfy_His_Service.Models;
using Lzfy_His_Service.Repositories;

namespace Lzfy_His_Service.Services
{
    public class UserManagementService : IUserManagementService
    {
        private readonly IUserRepository _userRepository;
        private readonly IRoleRepository _roleRepository;
        private readonly IPermissionRepository _permissionRepository;
        private readonly IAuthService _authService;

        public UserManagementService(
            IUserRepository userRepository, 
            IRoleRepository roleRepository,
            IPermissionRepository permissionRepository,
            IAuthService authService)
        {
            _userRepository = userRepository;
            _roleRepository = roleRepository;
            _permissionRepository = permissionRepository;
            _authService = authService;
        }

        public async Task<UserListResponse> GetUserListAsync(UserListRequest request)
        {
            return await _userRepository.GetUserListAsync(request);
        }

        public async Task<UserDto?> GetUserByIdAsync(int id)
        {
            var user = await _userRepository.GetUserByIdAsync(id);
            if (user == null) return null;

            var userRoles = await _userRepository.GetUserRolesAsync(id);
            List<string>? roleNames = userRoles?.Select(r => r.RoleName).ToList();

            return new UserDto
            {
                Id = user.Id,
                Username = user.Username,
                Email = user.Email,
                FullName = user.FullName ?? string.Empty,
                IsActive = user.IsActive,
                CreatedAt = user.CreatedAt,
                LastLoginAt = user.LastLoginAt,
                RoleNames = roleNames ?? new List<string>()
            };
        }

        public async Task<int> CreateUserAsync(UserDto userDto)
        {
            // 验证用户名是否已存在
            if (await _userRepository.UsernameExistsAsync(userDto.Username))
            {
                throw new InvalidOperationException("用户名已存在");
            }

            // 创建用户
            var user = new User
            {
                Username = userDto.Username,
                PasswordHash = _authService.HashPassword("123456"), // 默认密码
                Email = userDto.Email,
                FullName = userDto.FullName,
                Role = "User", // 默认角色
                IsActive = userDto.IsActive,
                CreatedAt = DateTime.Now,
                UpdatedAt = DateTime.Now
            };

            return await _userRepository.AddUserAsync(user);
        }

        public async Task<bool> UpdateUserAsync(int id, UserDto userDto)
        {
            // 验证用户是否存在
            var existingUser = await _userRepository.GetUserByIdAsync(id);
            if (existingUser == null)
            {
                throw new InvalidOperationException("用户不存在");
            }

            // 验证用户名是否已被其他用户使用
            if (await _userRepository.UsernameExistsAsync(userDto.Username, id))
            {
                throw new InvalidOperationException("用户名已存在");
            }

            // 更新用户信息
            existingUser.Username = userDto.Username;
            existingUser.Email = userDto.Email;
            existingUser.FullName = userDto.FullName;
            existingUser.IsActive = userDto.IsActive;
            existingUser.UpdatedAt = DateTime.Now;

            return await _userRepository.UpdateUserAsync(existingUser);
        }

        public async Task<bool> DeleteUserAsync(int id)
        {
            // 验证用户是否存在
            var existingUser = await _userRepository.GetUserByIdAsync(id);
            if (existingUser == null)
            {
                throw new InvalidOperationException("用户不存在");
            }

            return await _userRepository.DeleteUserAsync(id);
        }

        public async Task<bool> ToggleUserStatusAsync(int id, bool isActive)
        {
            // 验证用户是否存在
            var existingUser = await _userRepository.GetUserByIdAsync(id);
            if (existingUser == null)
            {
                throw new InvalidOperationException("用户不存在");
            }

            return await _userRepository.ToggleUserStatusAsync(id, isActive);
        }

        public async Task<bool> ResetUserPasswordAsync(int id, string newPassword)
        {
            // 验证用户是否存在
            var existingUser = await _userRepository.GetUserByIdAsync(id);
            if (existingUser == null)
            {
                throw new InvalidOperationException("用户不存在");
            }

            // 加密新密码
            var hashedPassword = _authService.HashPassword(newPassword);
            return await _userRepository.ResetPasswordAsync(id, hashedPassword);
        }

        public async Task<bool> AssignUserRolesAsync(int userId, List<int> roleIds)
        {
            // 验证用户是否存在
            var existingUser = await _userRepository.GetUserByIdAsync(userId);
            if (existingUser == null)
            {
                throw new InvalidOperationException("用户不存在");
            }

            // 验证角色是否都存在
            foreach (var roleId in roleIds)
            {
                var role = await _roleRepository.GetRoleByIdAsync(roleId);
                if (role == null)
                {
                    throw new InvalidOperationException($"角色ID {roleId} 不存在");
                }
            }

            return await _userRepository.AssignUserRolesAsync(userId, roleIds);
        }

        public async Task<List<UserRoleDto>> GetUserRolesAsync(int userId)
        {
            // 验证用户是否存在
            var existingUser = await _userRepository.GetUserByIdAsync(userId);
            if (existingUser == null)
            {
                throw new InvalidOperationException("用户不存在");
            }

            return await _userRepository.GetUserRolesAsync(userId);
        }

        public async Task<List<MenuDto>> GetUserPermissionsAsync(int userId)
        {
            // 验证用户是否存在
            var existingUser = await _userRepository.GetUserByIdAsync(userId);
            if (existingUser == null)
            {
                throw new InvalidOperationException("用户不存在");
            }

            return await _permissionRepository.GetUserMenusAsync(userId);
        }
    }
}